package com.jr.service.impl;

import com.jr.mapper.CareProviderMapper;
import com.jr.mapper.PetOwnerMapper;
import com.jr.pojo.CareProvider;
import com.jr.pojo.PetOwner;
import com.jr.pojo.User;
import com.jr.service.RegistrationService;
import com.jr.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

@Service
public class RegistrationServiceImpl implements RegistrationService {

    @Autowired
    private UserService userService;
    
    @Autowired
    private PetOwnerMapper petOwnerMapper;
    
    @Autowired
    private CareProviderMapper careProviderMapper;

    // 邮箱验证正则表达式
    private static final String EMAIL_PATTERN = 
        "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
    
    // 手机号验证正则表达式
    private static final String PHONE_PATTERN = "^1[3-9]\\d{9}$";

    @Override
    @Transactional
    public Map<String, Object> registerUser(User user, Map<String, Object> additionalInfo) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 1. 验证基础数据
            Map<String, Object> validation = validateRegistrationData(user);
            if (!(Boolean) validation.get("success")) {
                return validation;
            }
            
            // 2. 检查用户名和邮箱是否已存在
            if (userService.getUserByUsername(user.getUsername()) != null) {
                result.put("success", false);
                result.put("message", "用户名已存在");
                return result;
            }
            
            if (userService.getUserByEmail(user.getEmail()) != null) {
                result.put("success", false);
                result.put("message", "邮箱已存在");
                return result;
            }
            
            // 3. 插入用户基础信息
            boolean userInserted = userService.insertUser(user);
            if (!userInserted) {
                result.put("success", false);
                result.put("message", "用户基础信息创建失败");
                return result;
            }
            
            // 4. 获取新创建的用户信息（包含生成的userId）
            User newUser = userService.getUserByUsername(user.getUsername());
            if (newUser == null) {
                result.put("success", false);
                result.put("message", "无法获取新创建的用户信息");
                return result;
            }
            
            // 5. 根据用户类型创建相应的详细信息
            boolean detailCreated = createUserTypeSpecificInfo(newUser, additionalInfo);
            if (!detailCreated) {
                result.put("success", false);
                result.put("message", "用户详细信息创建失败");
                return result;
            }
            
            // 6. 返回成功结果
            result.put("success", true);
            result.put("message", "注册成功");
            newUser.setPassword(null); // 不返回密码
            result.put("user", newUser);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "注册失败：" + e.getMessage());
            System.err.println("Registration error: " + e.getMessage());
        }
        
        return result;
    }

    @Override
    public Map<String, Object> validateRegistrationData(User user) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查必填字段
        if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
            result.put("success", false);
            result.put("message", "用户名不能为空");
            return result;
        }
        
        if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
            result.put("success", false);
            result.put("message", "密码不能为空");
            return result;
        }
        
        if (user.getEmail() == null || user.getEmail().trim().isEmpty()) {
            result.put("success", false);
            result.put("message", "邮箱不能为空");
            return result;
        }
        
        if (user.getUserType() == null || user.getUserType().trim().isEmpty()) {
            result.put("success", false);
            result.put("message", "用户类型不能为空");
            return result;
        }
        
        // 验证用户名长度
        if (user.getUsername().length() < 3 || user.getUsername().length() > 20) {
            result.put("success", false);
            result.put("message", "用户名长度必须在3-20个字符之间");
            return result;
        }
        
        // 验证密码强度
        if (user.getPassword().length() < 6) {
            result.put("success", false);
            result.put("message", "密码长度不能少于6位");
            return result;
        }
        
        // 验证邮箱格式
        if (!Pattern.compile(EMAIL_PATTERN).matcher(user.getEmail()).matches()) {
            result.put("success", false);
            result.put("message", "邮箱格式不正确");
            return result;
        }
        
        // 验证手机号格式（如果提供）
        if (user.getPhone() != null && !user.getPhone().trim().isEmpty()) {
            if (!Pattern.compile(PHONE_PATTERN).matcher(user.getPhone()).matches()) {
                result.put("success", false);
                result.put("message", "手机号格式不正确");
                return result;
            }
        }
        
        // 验证用户类型
        if (!"pet_owner".equals(user.getUserType()) && 
            !"care_provider".equals(user.getUserType()) && 
            !"platform_admin".equals(user.getUserType())) {
            result.put("success", false);
            result.put("message", "无效的用户类型");
            return result;
        }
        
        result.put("success", true);
        result.put("message", "验证通过");
        return result;
    }

    /**
     * 根据用户类型创建相应的详细信息
     */
    private boolean createUserTypeSpecificInfo(User user, Map<String, Object> additionalInfo) {
        try {
            switch (user.getUserType()) {
                case "pet_owner":
                    return createPetOwnerInfo(user, additionalInfo);
                case "care_provider":
                    return createCareProviderInfo(user, additionalInfo);
                case "platform_admin":
                    // 平台管理员不需要额外的详细信息表
                    return true;
                default:
                    return false;
            }
        } catch (Exception e) {
            System.err.println("Error creating user type specific info: " + e.getMessage());
            return false;
        }
    }

    /**
     * 创建宠物主人详细信息
     */
    private boolean createPetOwnerInfo(User user, Map<String, Object> additionalInfo) {
        try {
            PetOwner petOwner = new PetOwner();
            petOwner.setUserId(user.getUserId());
            
            // 从额外信息中获取数据，设置默认值
            if (additionalInfo != null) {
                petOwner.setRealName((String) additionalInfo.getOrDefault("realName", user.getUsername()));
                petOwner.setIdCard((String) additionalInfo.get("idCard"));
                petOwner.setAddress((String) additionalInfo.get("address"));
                petOwner.setEmergencyContact((String) additionalInfo.get("emergencyContact"));
                petOwner.setEmergencyPhone((String) additionalInfo.get("emergencyPhone"));
            } else {
                petOwner.setRealName(user.getUsername());
            }
            
            petOwner.setCreatedAt(LocalDateTime.now());
            petOwner.setUpdatedAt(LocalDateTime.now());
            
            return petOwnerMapper.insertPetOwner(petOwner) > 0;
        } catch (Exception e) {
            System.err.println("Error creating pet owner info: " + e.getMessage());
            return false;
        }
    }

    /**
     * 创建服务提供商详细信息
     */
    private boolean createCareProviderInfo(User user, Map<String, Object> additionalInfo) {
        try {
            CareProvider careProvider = new CareProvider();
            careProvider.setUserId(user.getUserId());
            
            // 从额外信息中获取数据，设置默认值
            if (additionalInfo != null) {
                careProvider.setBusinessName((String) additionalInfo.getOrDefault("businessName", "待完善"));
                careProvider.setBusinessLicense((String) additionalInfo.get("businessLicense"));
                careProvider.setContactPerson((String) additionalInfo.getOrDefault("contactPerson", user.getUsername()));
                careProvider.setBusinessAddress((String) additionalInfo.getOrDefault("businessAddress", "待完善"));
                careProvider.setServiceArea((String) additionalInfo.get("serviceArea"));
                
                Object capacityObj = additionalInfo.get("capacity");
                if (capacityObj instanceof Integer) {
                    careProvider.setCapacity((Integer) capacityObj);
                } else {
                    careProvider.setCapacity(10); // 默认容量
                }
            } else {
                careProvider.setBusinessName("待完善");
                careProvider.setContactPerson(user.getUsername());
                careProvider.setBusinessAddress("待完善");
                careProvider.setCapacity(10);
            }
            
            // 设置默认值
            careProvider.setRating(BigDecimal.ZERO);
            careProvider.setReviewCount(0);
            careProvider.setStatus("pending"); // 待审核状态
            careProvider.setCreatedAt(LocalDateTime.now());
            careProvider.setUpdatedAt(LocalDateTime.now());
            
            return careProviderMapper.insertCareProvider(careProvider) > 0;
        } catch (Exception e) {
            System.err.println("Error creating care provider info: " + e.getMessage());
            return false;
        }
    }
}
